package tr.com.netgis.web;

import java.util.List;

import tr.com.netgis.NGApplication;
import tr.com.netgis.SharedPrefs;
import tr.com.netgis.db.NGDbHelper;
import tr.com.netgis.pojo.Message;
import tr.com.netgis.pojo.Message.Command;
import tr.com.netgis.pojo.NGLocation;
import tr.com.netgis.util.Constants;
import tr.com.netgis.util.Utility;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;

/**
 * When a response is get from request send, 
 * this handler makes afterward operations
 * @author NetGis
 *
 */
public class RequestHandler implements ISetLocationRequestHandler {

	protected NGDbHelper mHelper;
	protected SQLiteDatabase mDb;
	private SetLocationRequest request;
	
	public RequestHandler(SetLocationRequest request) {
		super();
		this.request = request;
		initializeDB();
	}

	public ISetLocationRequest getRequest() {
		return request;
	}

	public void setRequest(SetLocationRequest request) {
		this.request = request;
	}

	private void initializeDB (){
		mHelper = new NGDbHelper(NGApplication.getAppContext());	
		mDb = mHelper.getWritableDatabase();		
	}
	
	public void finish() {
		try {
			mHelper.close();
			mDb.close();
		} catch (Exception e) {
		}
	}
	
	class LoginTask extends AsyncTask<Void, Void, LoginResponse> {

		private LoginResponse postData(){
	    	SharedPrefs prefs = SharedPrefs.getInstance();
	    	String password = prefs.getPassword();
	    	String userName = prefs.getUserName();
	    	LoginRequest loginRequest = new LoginRequest();
	    	loginRequest.setPassword(password);
	    	loginRequest.setUserName(userName);
	    	loginRequest.setShowFailureNotification(true);
	    	loginRequest.setServerUrl(Constants.SERVER_URL);
	    	return WebServisCaller.callWebService(loginRequest);    	
	    }
		
		protected LoginResponse doInBackground(Void... vs) {
			return postData();
		}

		protected void onProgressUpdate(Void... progress) {
		}

		protected void onPostExecute(LoginResponse response) {
			Log.i("Request Handler", "Login task executed. Session ID: " + response.getSessionId());
		}
	};
	
	public void call(SetLocationResponse response) {
		NGLocation location = this.request.getLocation();
		
		try {
			ErrorCode errorCode = response.getErrorCode();
			if (ErrorCode.INVALID_SESSION.equals(errorCode)) {
				new LoginTask().execute();
			}
		} catch (Exception e) {
			Log.w("Request Handler", e.getMessage(), e);
		}
		
		if (request instanceof SendMessageRequest) {
			finish();
			return;
		}
		
		try {
			mHelper.insertForLog(location);								
		} catch (Exception e) {
			Log.w("Request Handler", e.getMessage(), e);
		}
		
		try {
			if (response.hasException() && location != null) {
				location.setSent(NGLocation.UNSENT);
				mHelper.insertUnsentLocation(this.request.getLocation());
			}
			
			if (response.isSuccessful()) {
				List<Message> messages = response.getMessages();
				if (Utility.isNotEmpty(messages)) {
					NGApplication.showNotification(Constants.APP_NAME + " Mesajları",  messages.size() + " tane mesaj geldi.");
					Log.d("MESAJLAR", messages.toString());
					mHelper.insertMessages(response.getMessages());
					processCommands(response.getCommands());							
				}
			}			
		} catch (Exception e) {
			Log.w("Request Handler", e.getMessage(), e);
		}
		
		try {
			mHelper.close();
			mDb.close();			
		} catch (Exception e) {
			Log.w("Request Handler", e.getMessage(), e);
		}
	}
	
	private void processCommands (List<Command> commands) {
		try {
			SharedPrefs sp = SharedPrefs.getInstance();
			for (Command command : commands) {
				tr.com.netgis.util.Command commandEnum = command.getCommand();
				if (command == null || !commandEnum.isUsedForDevice())
					continue;
				int value = tr.com.netgis.util.Command.validate(commandEnum, command.getValue());
				if (tr.com.netgis.util.Command.MIN_TIME.equals(commandEnum)) {
					sp.setMinTime(value);
				} else if (tr.com.netgis.util.Command.MIN_DISTANCE.equals(commandEnum)) {
					sp.setMinDistance(value);
				} else if (tr.com.netgis.util.Command.SEND_FREQUENCY.equals(commandEnum)) {
					sp.setSendFrequency(command.getValue());
				} else if (tr.com.netgis.util.Command.LOCATION_SIZE.equals(commandEnum)) {
					sp.setLocationSize(value);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	private class CallTask extends AsyncTask<SetLocationResponse, Void, String> {
		@Override
		protected String doInBackground(SetLocationResponse... responses) {
			List<Message> messages = new ArrayList<Message>();
			for (SetLocationResponse response : responses) {
				messages.addAll(response.getMessages());
			}
			mHelper.insertMessage(messages);
			return messages.size() + " tane mesaj kaydedildi.";
		}

		@Override
		protected void onPostExecute(String result) {
			Log.i ("RequetHandler", result);
			try {
				mHelper.close();
				mDb.close();			
			} catch (Exception e) {
			}
		}
	}
	*/
	
}
